import { debounce } from '@/utils/helper';
import {filterTel,trim} from '@/utils/index';
import {loginBack} from '@/utils/loginBack'
import { Image, Input, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import '../h5-login.scss';

const MobileLogin = ({ sendResult, toggle, agreementInfoLogin }) => {
  const [val, setVal] = useState({});
  const appConfig = Taro.getStorageSync('appConfig') || {}

  const [getCodeText, setGetCodeText] = useState('获取验证码');
  const cutDownTime = useRef(60); //60s
  const lock = useRef(false);

  const inputHandler = (key, e) => {
    setVal({ ...val, [key]: e.detail.value });
  };

  const getCode = debounce(() => {
    if (lock.current) {
      return;
    }
    if (getCodeText != '获取验证码') {
      return;
    }
    if (!filterTel(val.mobile)) {
      Taro.showToast({
        title: '请填写正确的手机号',
        icon: 'none',
      });
      return;
    }
    lock.current = true;
    
    Taro.$post('/notification/codes/login',{
      recv: val.mobile,
      verifyValue: '11111',
    }).then(res=>{
      if(res.code == '1'){
        Taro.$toast('发送成功')
        setGetCodeText(`${cutDownTime.current}s后重新获取`);
        let timer = setInterval(function () {
          cutDownTime.current--;
          if (cutDownTime.current <= 0) {
            clearInterval(timer);
            setGetCodeText('获取验证码');
            cutDownTime.current = 60;
            lock.current = false;
            return;
          }
          setGetCodeText(`${cutDownTime.current}s后重新获取`);
        }, 1000);
      }else{
        Taro.$toast(res.message)
      }
    })
  }, 2000);

  const loginByMobile = () => {
    if (!filterTel(val.mobile)) {
      Taro.showToast({
        title: '请填写正确的手机号',
        icon: 'none',
      });
      return;
    }
    if (!trim(val.code)) {
      Taro.showToast({
        title: '请填写验证码',
        icon: 'none',
      });
      return;
    }

    // if (agreementInfoLogin?.agreements?.length > 0 && !agreementInfoLogin?.isSelected) {
    //   Taro.showToast({
    //     title: '请勾选并同意协议条款',
    //     icon: 'none',
    //   });
    //   return;
    // }

    Taro.$post('/mb/logins',{
      username: val.mobile,
      password: val.code,
      loginType: 'USER_MOBILE',
    }).then(res=>{
      if(res.code == '1'){
        Taro.$toast('登录成功','success')
        setTimeout(() => {
          const timestamp = new Date().getTime();
          if(res.content.userSource == 'USER'){
            Taro.setStorageSync('user',{
              ...res.content,
              loginType: 'USER_MOBILE',
              timestamp
            });
          }
          Taro.setStorageSync('userSource',res.content.userSource)
          Taro.setStorageSync('token',res.content.token.accessToken)
          Taro.eventCenter.trigger('updateLogin')
          loginBack()
        }, 1000);
      }else{
        Taro.$toast(res.message)
      }
    })
  };

  return (
    <View className='H5Login H5MobileLogin'>
      <Image src={appConfig?.iconUrl || require('@/images/gray.jpg')} className="logo" />

      <View className="form">
        <View className="line">
          <Input
            className="input"
            type="number"
            value={val.mobile}
            placeholder="请输入您的手机号"
            placeholderClass="input-placeholder"
            onInput={(e) => {
              inputHandler('mobile', e);
            }}
          />
        </View>

        <View className="split-line"></View>

        <View className="line">
          <Input
            className="input"
            type="number"
            value={val.code}
            placeholder="请输入验证码"
            placeholderClass="input-placeholder"
            onInput={(e) => {
              inputHandler('code', e);
            }}
          />

          <View
            className={classNames('action', {
              'getting customePageStyle': getCodeText == '获取验证码',
              disabled: !filterTel(val.mobile),
            })}
            onClick={getCode}
          >
            {getCodeText}
          </View>
        </View>

        <View className="split-line"></View>
      </View>

      <View
        className={classNames('btn-login', {
          'disabled':
            !val.mobile ||
            !val.code ||
            (agreementInfoLogin?.agreements?.length > 0 && !agreementInfoLogin?.isSelected),
        })}
        onClick={loginByMobile}
      >
        <View className="txt">登录</View>
      </View>

      <View className="toggle" onClick={toggle}>
        账号密码登录
      </View>

      <View className="notice">未注册的手机号验证后自动创建账户</View>

    </View>
  );
};
export default MobileLogin;